<template>
  <div>
    <el-form ref="form" :model="searchForm" :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.username" placeholder="请输入要查询的用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchUserInfo">搜索</el-button>
        <el-button type="primary" @click="dialogFormVisible=true">新建</el-button>
        <el-popconfirm title="确认要批量删除吗！！！！" @confirm="deleteUser">
          <el-button slot="reference" type="danger" :disabled="deleteAllBtnStu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <!--  信息表格-->
    <el-table :data="tableData" border stripe style="width: 100%" :cell-style="{padding:'2px'}"
              @selection-change="selectionChange">
      <el-table-column type="selection" width="50">
      </el-table-column>
      <el-table-column label="头像" width="55">
        <!--      scope代表循环中的每一行-->
        <template slot-scope="scope">
          <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="120" prop="username">
      </el-table-column>
      <el-table-column label="角色" width="250" prop="username">
        <template slot-scope="scope">
          <!--          <el-tag size="mini">标签一</el-tag>-->
          <el-tag v-for="(role,index) in scope.row.roles" :key="role.id" style="margin-right: 4px">
            {{ role.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email" width="220">
      </el-table-column>
      <el-table-column label="电话" prop="tel" width="170">
      </el-table-column>
      <el-table-column label="状态" width="72">
        <template slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.statu===1 " type="success">正常</el-tag>
          <el-tag size="mini" v-else-if="scope.row.statu===0 " type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created" width="220">
        <template slot-scope="scope">
          {{ scope.row.created | fmtDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="340">
        <template slot-scope="scope">
          <el-button type="text">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="editUser(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="resetPass(scope.row.id,scope.row.username)">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="确认要删除吗！！！！" @confirm="deleteUser(scope.row.id)">
            <el-button slot="reference" type="text">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <el-pagination layout="prev, sizes,pager, next, total, jumper " :total="total" :page-size="size"
                   :page-sizes="[5,10,15,20]" :current-page="current" style="margin-top: 20px">
    </el-pagination>
    <!--    新建和修改的表单-->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="600px" :before-close="handleClose">
      <el-form :model="UserForm" ref="UserForm" label-width="100px" :rules="rules">
        <el-form-item label="用户头像" label-width="100px">
          <el-upload
              class="avatar-uploader" action="/api/upload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :headers="headers">
            <img v-if="UserForm.avatar" :src="UserForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input v-model="UserForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="100px" prop="email">
          <el-input v-model="UserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" label-width="100px" prop="tel">
          <el-input v-model="UserForm.tel" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" label-width="100px">
          <el-radio-group v-model="UserForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('UserForm')">保存用户</el-button>
        <el-button type="primary" @click="resetForm('UserForm')">重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  props: {},
  data() {
    return {
      selection: [],
      dialogFormVisible: false,
      //用户对象显示的数据，就是数据库查出来的
      tableData: [],
      total: 0,
      size: 10,
      current: 1,
      //批量删除
      deleteAllBtnStu: true,
      //搜索框
      searchForm: {},
      UserForm: {},
      //针对上传头像对服务器的请求，需携带请求头
      headers: {
        token: localStorage.getItem('token')
      },
      rules: {
        username: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ]
      }
    };
  },
  watch: {},
  computed: {},
  methods: {
    resetPass(id, name) {
      this.$confirm('确认重置用户' + name + '的密码，是否执行该操作！！！', '重置密码操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(_ => {
        this.$axios.post('/system/user/repass', id).then((response) => {
          this.$message({
            message: response.data.message,
            type: 'success',
            showClose: true,
          });
        })
      })
    },
    editUser(id) {
      this.$axios('/user/userInfo/' + id).then(response => {
        this.UserForm = response.data.data
        this.dialogFormVisible = true
      })
    },
    loadUserList() {
      this.$axios.get('/system/user/list', {
        current: this.current,
        size: this.size,
      }).then(response => {
        //获得分页的用户信息
        this.tableData = response.data.data.records
        //获得服务器返回的分页数据
        this.total = response.data.data.total
        this.size = response.data.data.size
        this.current = response.data.data.current
      })
    },
    deleteUser(id) {
      let ids = [];
      id ? ids.push(id) : this.selection.forEach(u => {
        ids.push(u.id)
      })
      this.$axios.post('/system/user/delete', ids).then(response => {
        this.$message({
          message: response.data.message,
          type: 'success',
          showClose: true,
          onClose: () => {
            this.loadUserList()
          }
        });
      })
    },
    searchUserInfo() {

    },
    //关闭对话框时重置表单
    handleClose() {
      this.dialogFormVisible = false;
      this.resetForm()

    },
    //用户头像上传成功回调
    handleAvatarSuccess(response, file) {
      this.UserForm.avatar = response.data
    },
    submitForm(formName) {
      this.$refs.UserForm.validate(valid => {
        if (valid) {
          this.$axios.post('/system/user/' + (this.UserForm.id ? 'update' : 'save'), this.UserForm).then(response => {
            this.$message({
              message: response.data.message,
              type: 'success',
              // showClose: true,
              duration:1000,
              onClose: () => {
                this.loadUserList()
                this.dialogFormVisible = false
                this.resetForm(formName)
              }
            })
          })
        }
      })
    },
    // resetFrom(formName) {
    //   this.UserForm = {}
    //   this.$refs.fromName.resetFields();
    //   this.dialogFormVisible = false
    // },
    resetForm() {
      this.UserForm = {}
      this.$refs.UserForm.resetFields();
    },
    //选中的一行用户数据
    selectionChange(value) {
      this.selection = value;
      if (this.selection) {
        this.deleteAllBtnStu = (this.selection.length === 0)
      }
    },
  },
  created() {
    this.loadUserList();
  },
  mounted() {
    this.loadUserList()
  },
  filters: {
    fmtDate: (value) => {
      let date = new Date(value)
      let y = date.getFullYear()
      let M = (date.getMonth() + 1).toString().padStart(2, '0')
      let d = date.getDate().toString().padStart(2, '0')
      let h = date.getHours().toString().padStart(2, '0')
      let m = date.getMinutes().toString().padStart(2, '0')
      let s = date.getSeconds().toString().padStart(2, '0')
      return `${y}年${M}月${d}日 ${h}:${m}:${s}`
    }
  }
};
</script>

<style scoped>
.el-table__body {
  font-size: 14px;
}

.el-button:hover {
  color: #333
}

.el-popconfirm-reference {
  cursor: pointer;
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  font-size: 12px;
  padding: 2px 6px;
}

.el-table-column--selection {
  text-align: center;
}

.el-avatar {
  border-radius: 50%;
}

.el-divider {
  margin: 0 6px;
}

/*上传头像*/
/*.avatar-uploader {*/
/*  border: 1px dashed #d9d9d9;*/
/*  border-radius: 6px;*/
/*  cursor: pointer;*/
/*  position: relative;*/
/*  overflow: hidden;*/
/*}*/

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-dialog {
  text-align: center;
}

/* Style the dialog header */
.el-dialog__header {
  background-color: #2f4050;
  color: #fff;
  border-radius: 4px 4px 0 0;
  border-bottom: none;
}

/* Style the dialog title */
.el-dialog__title {
  font-size: 22px;
  font-weight: bold;
  padding: 20px;
}

/* Style the form labels */
.el-form-item__label {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

/* Style the input fields */
.el-input__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: #606266;
}

/* Style the radio buttons */


.el-radio-button {
  flex: 1;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
  border-radius: 0 0 4px 4px;
}

.dialog-footer .el-button {
  margin-left: 10px;
  border-radius: 4px;
}

.dialog-footer .el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.dialog-footer .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.dialog-footer .el-button--primary:active {
  background-color: #3a8ee6;
  border-color: #3a8ee6;
}

.dialog-footer .el-button--default {
  color: #333;
  border-color: #dcdfe6;
}

.dialog-footer .el-button--default:hover {
  color: #409EFF;
  border-color: #409EFF;
}

</style>